package com.css.fxfzaqbz.base.dict.repository.impl;

import com.css.fxfzaqbz.base.dict.repository.DictRepository;
import com.css.fxfzaqbz.base.dict.repository.entity.DictEntity;
import com.css.fxfzaqbz.base.dict.viewobjects.DictQueryParams;
import com.css.fxfzaqbz.util.PlatformObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DictRepositoryImpl implements DictRepository {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public Page<DictEntity> queryDicts(DictQueryParams queryParams, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from sys_dict ");
        StringBuilder whereSql = new StringBuilder("where 1=1 ");
        if(!PlatformObjectUtils.isEmpty(queryParams.getDictDirId())){
            whereSql.append(" and dict_dir_id = "+ queryParams.getDictDirId() );
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getDictName())){
            whereSql.append(" and dict_name like %"+ queryParams.getDictName() +"%");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getDictCode())){
            whereSql.append(" and dict_code like %"+ queryParams.getDictCode() +"%");
        }
        StringBuilder orderSql = new StringBuilder(" order by sort");

        String sqlWhole = sql.append(whereSql).append(orderSql).toString();

        List<DictEntity> dictEntities = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(DictEntity.class));

        Pageable pageable = PageRequest.of(curPage - 1 ,pageSize);

        Page<DictEntity> dicts = new PageImpl<DictEntity>(dictEntities, pageable, PlatformObjectUtils.isEmpty(dictEntities)? 0 : dictEntities.size());
        return dicts;
    }

    @Override
    @Transactional
    public void saveDict(DictEntity dictEntity) {
        StringBuilder sql = new StringBuilder();
        if (PlatformObjectUtils.isNotEmpty(dictEntity) && PlatformObjectUtils.isNotEmpty(dictEntity.getDictId()) && PlatformObjectUtils.isNotEmpty(findById(dictEntity.getDictId())) ){
            sql.append("update sys_dict set dict_code = :dictCode, dict_name = :dictName, dict_dir_id = :dictDirId, " +
                    "sort = :sort, is_valid = :isValid, description = :description, update_user = :updateUser, update_time = :updateTime " +
                    "where dict_id = :dictId ");
            /*Map params = new HashMap();
            params.put("dictCode", dictEntity.getDictCode());
            params.put("dictId", dictEntity.getDictId());
            namedParameterJdbcTemplate.update(updateSql.toString(), params);*/
        }else {
            sql.append("insert into sys_dict values(:dictId, :dictCode, :dictName, :dictDirId, :sort, :isValid\n" +
                    ", :description, :createUser, :createTime, :updateUser, :updateTime ) ");
        }
        SqlParameterSource source = new BeanPropertySqlParameterSource(dictEntity);
        namedParameterJdbcTemplate.update(sql.toString(), source);
    }

    @Override
    public String findDictCodeByDictId(String dictId) {
        StringBuilder sql = new StringBuilder("select dict_code from sys_dict where dict_id = '"+ dictId +"'");
        try {
            String dictCode = jdbcTemplate.queryForObject(sql.toString(), String.class);
            return dictCode;
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    @Override
    public DictEntity findById(String id) {
        String sql = "select * from sys_dict where dict_id = '"+ id +"'";
        try {
            DictEntity dictEntity = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(DictEntity.class));
            return dictEntity;
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    @Override
    public DictEntity findOneByDictCode(String dictCode) {
        StringBuilder sql = new StringBuilder("select * from sys_dict where dict_code = '"+ dictCode +"' and is_valid='1'");
        try {
            DictEntity dictEntity = jdbcTemplate.queryForObject(sql.toString(), new BeanPropertyRowMapper<>(DictEntity.class));
            return dictEntity;
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    @Override
    public DictEntity findOneByDictCodeAndIsValid(String dictCode, String isValid) {
        StringBuilder sql = new StringBuilder("select * from sys_dict where dict_code = '"+ dictCode +"' and is_valid = '"+ isValid +"'");
        try {
            DictEntity dictEntity = jdbcTemplate.queryForObject(sql.toString(), new BeanPropertyRowMapper<>(DictEntity.class));
            return dictEntity;
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    @Override
    public List<DictEntity> findAll() {
        StringBuilder sql = new StringBuilder("select * from sys_dict");
        List<DictEntity> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DictEntity.class));
        return list;
    }

    @Override
    @Transactional
    public void delete(List<String> ids) {
        StringBuilder sql = new StringBuilder("delete from sys_dict where dict_id in (:ids)");
        //Map idsMap = Collections.singletonMap("ids", ids);
        Map idMap = new HashMap();
        idMap.put("ids", ids);
        namedParameterJdbcTemplate.update(sql.toString(), idMap);
    }

    @Override
    public List<DictEntity> findAllById(List<String> ids) {
        StringBuilder sql = new StringBuilder("select * from sys_dict where dict_id in (:ids)");
        Map idMap = new HashMap();
        idMap.put("ids", ids);
        List list = namedParameterJdbcTemplate.query(sql.toString(), idMap, new BeanPropertyRowMapper<>(DictEntity.class));
        return list;
    }

    @Override
    public List<DictEntity> findByDictDirId(String dictDirId) {
        StringBuilder sql = new StringBuilder("select * from sys_dict where dict_dir_id = '"+ dictDirId +"' and is_valid='1' order by sort");
        List<DictEntity> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DictEntity.class));
        return list;
    }

    @Override
    public List<DictEntity> findByDictDirIdAndIsValid(String dictDirId, String isValid) {
        StringBuilder sql = new StringBuilder("select * from sys_dict where dict_dir_id = '"+ dictDirId +"' and is_valid = '"+ isValid +"'");
        List<DictEntity> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DictEntity.class));
        return list;
    }

    @Override
    public List<DictEntity> findByIsValid(String isValid) {
        StringBuilder sql = new StringBuilder("select * from sys_dict where is_valid = ?");
        List<DictEntity> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DictEntity.class), isValid);
        return list;
    }

    @Override
    public List<DictEntity> findAllByDirId(List<String> ids) {
        StringBuilder sql = new StringBuilder("select * from sys_dict where dict_dir_id IN (:ids)");
        Map idMap = new HashMap();
        idMap.put("ids", ids);
        List list = namedParameterJdbcTemplate.query(sql.toString(), idMap, new BeanPropertyRowMapper<>(DictEntity.class));
        return list;
    }
}
